package com.agile.leetcode.order.orderid;

import java.net.InetAddress;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/9/28 15:11
 */
public class GenerateOrderIdAtMulty {
    private volatile static String IP_SUFFIX = null;
    /**
     * 计数器
     */
    private static final AtomicInteger SEQUENCE = new AtomicInteger(1000);
    /**
     * 格式化时间
     * 保留两位毫秒数
     */
    private static final DateTimeFormatter DF_FMT_PREFIX = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSS");
    /**
     * 时区
     */
    private static ZoneId ZONE_ID = ZoneId.of("Asia/Shanghai");

    public static String generate() {
        // 当前时区的时间
        LocalDateTime localDateTime = LocalDateTime.now(ZONE_ID);
        if (SEQUENCE.intValue() > 9999) {
            SEQUENCE.getAndSet(1000);
        }
        return localDateTime.format(DF_FMT_PREFIX) + getLocalIpSuffix() + SEQUENCE.getAndIncrement();
    }

    private static String getLocalIpSuffix() {
        if (null != IP_SUFFIX) {
            return IP_SUFFIX;
        }
        try {
            synchronized (GenerateOrderIdAtMulty.class) {
                if (null != IP_SUFFIX) {
                    return IP_SUFFIX;
                }
                InetAddress addr = InetAddress.getLocalHost();
                // 拿到主机ip
                String hostAddress = addr.getHostAddress();
                if (null != hostAddress && hostAddress.length() > 4) {
                    String ipSuffix = hostAddress.trim().split("\\.")[3];
                    if (ipSuffix.length() == 2) {
                        IP_SUFFIX = ipSuffix;
                        return IP_SUFFIX;
                    }
                    ipSuffix = "0" + ipSuffix;
                    IP_SUFFIX = ipSuffix.substring(ipSuffix.length() - 2);
                    return ipSuffix;
                }
                IP_SUFFIX = new Random().nextInt(20) + "";
                return IP_SUFFIX;
            }
        } catch (Exception ex) {
            System.out.println("获取ip失败");
            IP_SUFFIX = new Random().nextInt(20) + "";
            return IP_SUFFIX;
        }
    }

    public static void main(String[] args) {
        List<String> list = Collections.synchronizedList(new ArrayList<>());
        IntStream.range(0, 8000).parallel().forEach((i) -> {
            list.add(generate());
        });
        List<String> filterOrderNos = list.stream().distinct().collect(Collectors.toList());
        System.out.println("生成订单数= " + list.size());
        System.out.println("不重复订单数为= " + filterOrderNos.size());
        System.out.println("重复订单数为= " + (list.size() - filterOrderNos.size()));
    }
}
